import axios from 'axios';
import https from 'https';
import { Message, Spin, Modal } from 'view-design';
import Storage from './storage.js';
import router from '../router/index.js';
import store from '../vuex/store.js';
import errorCode from './errorCode'
import { handleRefreshToken } from '@/api/index';
import { v4 as uuidv4 } from 'uuid';

const qs = require('qs');
// api地址
export const buyerUrl =
  process.env.NODE_ENV === 'development'
    ? BASE.API_DEV.buyer
    : BASE.API_PROD.buyer;
export const commonUrl =
  process.env.NODE_ENV === 'development'
    ? BASE.API_DEV.common
    : BASE.API_PROD.common;
export const managerUrl =
  process.env.NODE_ENV === 'development'
    ? BASE.API_DEV.manager
    : BASE.API_PROD.manager;
export const sellerUrl =
  process.env.NODE_ENV === 'development'
    ? BASE.API_DEV.seller
    : BASE.API_PROD.seller;
// 创建axios实例
// 
const service = axios.create({
  timeout: 10000, // 请求超时时间
  baseURL: buyerUrl, // API
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  }),
  paramsSerializer: params =>
    qs.stringify(params, {
      arrayFormat: 'repeat'
    })
});
// 是否显示重新登录
export let isRelogin = { show: false };
// request拦截器
service.interceptors.request.use(
  config => {
    const { loading } = config;
    // 如果是put/post请求，用qs.stringify序列化参数
    const isPutPost = config.method === 'put' || config.method === 'post';
    const isJson = config.headers['Content-Type'] === 'application/json';
    const isFile = config.headers['Content-Type'] === 'multipart/form-data';
    if (isPutPost && isJson) {
      config.data = JSON.stringify(config.data);
    }
    if (isPutPost && !isFile && !isJson) {
      config.data = qs.stringify(config.data, {
        arrayFormat: 'repeat'
      });
    }
    /** 配置全屏加载 */
    if (process.client && loading !== false) {
      config.loading = Spin.show();
    }

    let uuid = Storage.getItem('uuid');
    if (!uuid) {
      uuid = uuidv4();
      Storage.setItem('uuid', uuid);
    }
    config.headers['uuid'] = uuid;

    // 获取访问Token
    let accessToken = Storage.getItem('accessToken');
    if (accessToken && config.needToken) {
      config.headers['Authorization'] = accessToken;
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

async function refresh(msg) {
  Storage.removeItem('accessToken');
  Storage.removeItem('refreshToken');
  Storage.removeItem('userInfo');
  Storage.removeItem("roles");
  store.commit('SET_CARTNUM', 0);
  Modal.confirm({
    title: '请登录',
    content: `<p>${msg}</p>`,
    okText: '立即登录',
    cancelText: '继续浏览',
    onOk: () => {
      // isRelogin.show = false;
      router.push({
        path: '/login',
        query: {
          rePath: router.history.current.path,
          query: JSON.stringify(router.history.current.query)
        }
      });
    },
    onCancel: () => {
      // isRelogin.show = true;
      console.log(11111111, isRelogin.show);
      router.push("/");
      Modal.remove();
    }
  });
}

// respone拦截器
service.interceptors.response.use(
  res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        // isRelogin.show = true;
        refresh('登录状态已过期，您可以继续留在该页面，或者重新登录')
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
      // } else if (code === 500) {
      //   Message.error(msg)
      //   return Promise.reject(new Error(msg))
    } else if (code === 601) {
      Message.warning(msg)
      return Promise.reject('error')
    } else if (code !== 200) {
      Message.error(msg)
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let Error = error + '';
    console.log('err', Error, error)

    if (Error == "Network Error") {
      Error = "后端接口连接异常";
    } else if (Error.includes("timeout")) {
      Error = "系统接口请求超时";
    } else if (Error.includes("Request failed with status code")) {
      Error = "系统接口" + Error.substr(Error.length - 3) + "异常";
    }
    Message.error(Error);
    return Promise.reject(error)
  }
  // async response => {
  //   await closeLoading(response);

  //   return response.data;
  // },
  // async error => {
  //   if (process.server) return Promise.reject(error);
  //   await closeLoading(error);
  //   const errorResponse = error.response || {};
  //   const errorData = errorResponse.data || {};

  //   if (errorResponse.status === 401 || errorResponse.status === 403 || error.response.data.code === 20004) {
  //     isRefreshToken++;

  //     if (isRefreshToken === 1) {
  //       refresh(error)
  //       isRefreshToken = 0;
  //     }
  //   } else if (errorResponse.status === 404) {
  //     // 避免刷新token时也提示报错信息
  //   } else {
  //     if (error.message) {
  //       let _message =
  //         error.code === 'ECONNABORTED'
  //           ? '连接超时，请稍候再试！'
  //           : '网络错误，请稍后再试！';
  //       Message.error(errorData.message || _message);
  //     }
  //   }
  //   return Promise.reject(errorData);
  // }

);

/**
 * 关闭全局加载
 * @param target
 */
const closeLoading = target => {
  if (!target.config || !target.config.loading) return true;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      target.config.loading.hide();
      resolve();
    }, 200);
  });
};

export const Method = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete'
};

export default function request(options) {
  return service(options);
}
// 防抖闭包来一波
function getTokenDebounce() {
  let lock = false;
  let success = false;
  return function () {
    if (!lock) {
      lock = true;
      let oldRefreshToken = Storage.getItem('refreshToken');
      handleRefreshToken(oldRefreshToken)
        .then(res => {
          if (res.success) {
            let { accessToken, refreshToken } = res.result;
            Storage.setItem('accessToken', accessToken);
            Storage.setItem('refreshToken', refreshToken);

            success = true;
            lock = false;
          } else {
            success = false;
            lock = false;
            // router.push('/login')
          }
        })
        .catch(err => {
          console.log(err);
          success = false;
          lock = false;
        });
    }
    return new Promise(resolve => {
      // 一直看lock,直到请求失败或者成功
      const timer = setInterval(() => {
        if (!lock) {
          clearInterval(timer);
          if (success) {
            resolve('success');
          } else {
            resolve('fail');
          }
        }
      }, 500); // 轮询时间间隔
    });
  };
}
